<?php

namespace app\api\logic;
use app\data\util\HttpUtil;
use think\facade\Db;
class Info1688Logic extends BasicLogic
{


    /**
     * @desc    发起授权请求签名串组装
     * @date    2025-01-07
     * @author  zhangheng
     */
    public function get_1688_signature($params = [])
    {
        $appSecret = Config('Logisticskey.1688_info.AppSecret');
        $url       = $params['url']??'';
        // 使用 parse_url() 函数解析 URL
        $parsedUrl   = parse_url($url);
        $path        = str_replace('/openapi/', '', $parsedUrl['path']);
        $queryString = $parsedUrl['query']??'';
        $aliParams   = [];
        parse_str($queryString, $queryParams);
        foreach ($queryParams as $key => $val) {
            $aliParams[] = $key . $val;
        }
        sort($aliParams);
        $sign_str = $path.join('', $aliParams);
        return strtoupper(bin2hex(hash_hmac("sha1", $sign_str, $appSecret, true)));
    }


    /**
     * @desc   获取1688某个产品的sku信息
     * @author luckyXiong
     * @date   2025-01-06
     */
    public function get_product_skus($params = []){
           $product_id   = $params['product_id']??'';
           $base_url     = Config('Logisticskey.1688_info.base_url');
           $AppKey       = Config('Logisticskey.1688_info.AppKey');
           $access_token = Config('Logisticskey.1688_info.access_token');
           $url          = $base_url.Config('Logisticskey.1688_info.product_sku_url').$AppKey;
           $data         = [
               'offerId'       =>$product_id,
               'access_token'  =>$access_token,
           ];
           $signature_url           =  urladdparam($url,$data);
           $signature               =  self::get_1688_signature(['url'=>$signature_url]);
           $data['_aop_signature']  =  $signature;
           $list                    =  HttpUtil::doGets($url,$data);
           return $list ?: [];
    }

    /**
     * @desc   获取1688产品信息
     * @author luckyXiong
     * @date   2025-01-06
     */
    public function get_product_copy($params = []){
        $product_id   = $params['product_id']??'';
        $base_url     = Config('Logisticskey.1688_info.base_url');
        $AppKey       = Config('Logisticskey.1688_info.AppKey');
        $access_token = Config('Logisticskey.1688_info.access_token');
        $url          = $base_url.Config('Logisticskey.1688_info.product_url').$AppKey;
        $offerIds     = [];
        $offerIds[]   = intval($product_id);
        $data = [
            'offerIds'      =>json_encode($offerIds, JSON_UNESCAPED_UNICODE),
            'access_token'  =>$access_token,
        ];

        foreach ($data as $key => $value) {
            $data[$key] = urlencode($value);
        }
        $signature_url   = urladdparam($url,$data);
        $signature       = self::get_1688_signature(['url'=>$signature_url]);
        $data['_aop_signature']  =  $signature;
        $list   = HttpUtil::doGets($url,$data);
        $arr    = [];
        $sku_info = $list['result']['result'][0]['productInfo']['skuInfos']??[];
        if(empty($sku_info))  return [];
        foreach($sku_info as $v){
                $temp['varient_colour']     = $v['attributes'][0]['attributeValue']??'';
                $temp['1688_product_id']    = $product_id;
                $temp['1688_product_name']  = $list['result']['result'][0]['productInfo']['subject']??'';
                $temp['1688_product_image'] = isset($v['attributes'][0]['skuImageUrl']) && $v['attributes'][0]['skuImageUrl'] ? 'https://cbu01.alicdn.com/'.$v['attributes'][0]['skuImageUrl'] :'';
                $temp['varient_size']       = $v['attributes'][1]['attributeValue']??'';
                $temp['skuId']              = $v['skuId']??'';
                $temp['specId']             = $v['specId']??'';
                $arr[]                      = $temp;
        }
        return   $arr;
    }


    /**
     * @desc   获取1688产品信息接口
     * @author luckyXiong
     * @date   2025-02-27
     */
    public function get_product($params = []){
        $product_id   = $params['product_id']??'';
        $base_url     = Config('Logisticskey.1688_info.base_url');
        $AppKey       = Config('Logisticskey.1688_info.AppKey');
        $access_token = Config('Logisticskey.1688_info.access_token');
        $url          = $base_url.Config('Logisticskey.1688_info.product_url').$AppKey;
        $offerIds     = [];
        $offerIds[]   = intval($product_id);
        $data = [
            'offerIds'      =>json_encode($offerIds, JSON_UNESCAPED_UNICODE),
            'access_token'  =>$access_token,
        ];

        foreach ($data as $key => $value) {
            $data[$key] = urlencode($value);
        }
        $signature_url   = urladdparam($url,$data);
        $signature       = self::get_1688_signature(['url'=>$signature_url]);
        $data['_aop_signature']  =  $signature;
        $list   = HttpUtil::doGets($url,$data);
        $arr    = [];
        $sku_info = $list['result']['result'][0]['productInfo']['skuInfos']??[];
        if(empty($sku_info))  return [];
        foreach($sku_info as $v){
            $temp['varient_colour']     = $v['attributes'][0]['attributeValue']??'';
            $temp['1688_product_id']    = $product_id;
            $temp['1688_product_name']  = $list['result']['result'][0]['productInfo']['subject']??'';
            $temp['1688_product_image'] = isset($v['attributes'][0]['skuImageUrl']) && $v['attributes'][0]['skuImageUrl'] ? 'https://cbu01.alicdn.com/'.$v['attributes'][0]['skuImageUrl'] :'';
            $temp['varient_size']       = $v['attributes'][1]['attributeValue']??'';
            $temp['skuId']              = $v['skuId']??'';
            $temp['specId']             = $v['specId']??'';
            $arr[]                      = $temp;
        }
        return   $arr;
    }


    /**
     * @desc   查询采购单列表
     * @author zhangheng
     * @date   2025-01-06
     */
    public function PurchaseOrderList($params = []){
        $base_url     = Config('Logisticskey.1688_info.base_url');
        $AppKey       = Config('Logisticskey.1688_info.AppKey');
        $access_token = Config('Logisticskey.1688_info.access_token');
        $url          = $base_url.Config('Logisticskey.1688_info.PurchaseOrderList').$AppKey;
        $data         = [
            'pageStart'       =>1,
            'access_token'  =>$access_token,
        ];
        $signature_url   = urladdparam($url,$data);
        $signature       = self::get_1688_signature(['url'=>$signature_url]);
        $data['_aop_signature']  =  $signature;
        $list       = HttpUtil::doGets($url,$data);
        halt($list);
        return $list ?: [];
    }


    /**
     * @desc   1688订单取消接口
     * @author luckyXiong
     * @date   2025-02-27
     */
    public function cancelOrder($params = []){
        //1688订单号
        $order_number = $params['1688_order_number']??'';
        $access_token = Config('Logisticskey.1688_info.access_token');
        $base_url     = Config('Logisticskey.1688_info.base_url');
        $AppKey       = Config('Logisticskey.1688_info.AppKey');
        $url          = $base_url.Config('Logisticskey.1688_info.cancel_order').$AppKey;
        $data         = [
            'tradeID'       =>$order_number,
            'webSite'       =>'1688',
            'cancelReason'  =>'buyerCancel',
            'access_token'  =>$access_token,
        ];
        $signature_url   = urladdparam($url,$data);
        $signature       = self::get_1688_signature(['url'=>$signature_url]);
        $data['_aop_signature']  =  $signature;
        $res       = HttpUtil::doGets($url,$data);
        return $res;
    }


    /**
     * @desc   1688创建采购单接口
     * @author luckyXiong
     * @date   2025-02-08
     */
    public function createOrder($params = []){
        //1688订单号
        $access_token = Config('Logisticskey.1688_info.access_token');
        $base_url     = Config('Logisticskey.1688_info.base_url');
        $AppKey       = Config('Logisticskey.1688_info.AppKey');
        $url          = $base_url.Config('Logisticskey.1688_info.create_order').$AppKey;
        $tel          = '13871468530';
        $cargoParamList = [];

        //测试数据 02-10
        $addressParam = [
            "fullName"    => "帆洲科技",
            "mobile"      => $tel,
            "postCode"    => "430000",
            "cityText"    => "武汉市",
            "provinceText"=> "湖北省",
            "areaText"    => "江夏区",
            "address"     => "江夏区经济开发区庙山街道庙山开发区幸福村一新完美工业园2栋2单元3楼 （放门卫室直接投诉）",
        ];

        $sku_list  = [
            "offerId"  => 845965507173,
            "specId"   => "1b8eccc27b349f13ede10b8d8a6167ab",
            "quantity" => 1
        ];

        $cargoParamList[] =$sku_list;
        $data         = [
            'flow'          =>'general',
            'message'       =>'技术测试订单02-10',
            'addressParam'  =>json_encode($addressParam, JSON_UNESCAPED_UNICODE),
            'cargoParamList'=>json_encode($cargoParamList, JSON_UNESCAPED_UNICODE),
            'access_token'  =>$access_token,
        ];
        foreach ($data as $key => $value) {
            $data[$key] = urlencode($value);
        }
        $signature_url           = urladdparam($url,$data);
        $signature               = self::get_1688_signature(['url'=>$signature_url]);
        $data['_aop_signature']  = $signature;
        $response                = HttpUtil::doGets($url,$data);

        if (isset($response['success']) && $response['success']) {
            $res_info = $response['result']['orderId']??'';
        } else {
            $res_info = $response['errorMsg']??'';
        }
        return $res_info;
    }


    /**
     * @desc   获取1688单条商品信息
     * @author luckyXiong
     * @date   2025-03-24
     */
    public function get_1688_one($params){
           $sku_list = self::getProductByUrls($params);
           self::add_1688_url(['sku_list'=>$sku_list]);
           //推送分组数据过去
           return $sku_list;
    }



    /**
     * @desc   获取1688产品信息
     * @author luckyXiong
     * @date   2025-02-10
     */
    public function getProductByUrls($params = []){
           $url           = $params['url']??'';
           $product_id    = getOfferIdFromUrl($url);
           $info          = (new Vip1688Logic())->get_product_info(['product_id'=>$product_id]);
           $product_name  = $info['product_name']??'';
           $supply_name   = $info['supply_name']??'';
           $sku_info      = $info['sku_list']??'';
           $user_id       = $info['user_id']??'';
           if(empty($sku_info))  return [];
           if($supply_name){
            $exist_supply = Db::name('supply')->where(['supply_name'=>$supply_name])->find();
           }
           if(!$exist_supply){
            $supply_id = Db::name('supply')->insertGetId(
                [
                    'supply_name' =>$supply_name,
                    'user_id'     =>$user_id,
                    'created_time'=>date("Y-m-d H:i:s", time())
                ]);
        }else{
            $supply_id = $exist_supply['id'];
            Db::name('supply')->where(['id'=>$supply_id])->update(
                [
                    'user_id'     =>$user_id,
                ]);
        }
           foreach($sku_info as $v){
               $product_image              = $v['attributes'][0]['skuImageUrl']??'';
               $temp['1688_product_id']    = $product_id;
               $temp['1688_product_image'] = $product_image ? Config('Logisticskey.1688_info.image_url').$product_image:'';
               $temp['1688_product_url']   = Config('Logisticskey.1688_info.1688_url').$product_id.'.html';
               $temp['skuId']              = $v['skuId'];
               $temp['specId']             = $v['specId'];
               $temp['1688_product_name']  = $product_name;
               $temp['varient_colour']     = $v['attributes'][0]['attributeValue']??'';
               $temp['varient_size']       = $v['attributes'][1]['attributeValue']??'';
               $temp['supply_id']          = $supply_id;
               $temp['create_time']        = date("Y-m-d H:i:s", time());
               $arr[]                      = $temp;
        }
        return   $arr;
    }


    /**
     * @desc   单个商品保存接口
     * @author luckyXiong
     * @date   2025-02-10
     */
    public function add_1688_url($params = []){
           $sku_list   = $params['sku_list']??'';
           $current    = current($sku_list);
           $product_id = $current['1688_product_id']??'';
           $insert_arr = [];
           //获取表中是否存在数据;
           $exist_info = Db::name('product_1688')->where(['1688_product_id'=>$product_id])->column('skuId');
           if($exist_info){
               foreach($sku_list  as $v){
                       if(in_array($v['skuId'],$exist_info)){
                              continue;
                       }
                       $temp['1688_product_id']    = $v['1688_product_id'];
                       $temp['1688_product_image'] = $v['1688_product_image'];
                       $temp['skuId']              = $v['skuId'];
                       $temp['specId']             = $v['specId'];
                       $temp['supply_id']          = $v['supply_id'];
                       $temp['1688_product_url']   = 'https://detail.1688.com/offer/'.$v['1688_product_id'].'.html';
                       $temp['1688_product_name']  = $v['1688_product_name'];
                       $temp['varient_colour']     = $v['varient_colour'];
                       $temp['varient_size']       = $v['varient_size'];
                       $temp['create_time']        = date("Y-m-d H:i:s", time());
                       $insert_arr[]               = $temp;
               }
           }else{
               foreach($sku_list  as $v){
                   $temp['1688_product_id']    = $v['1688_product_id'];
                   $temp['1688_product_image'] = $v['1688_product_image'];
                   $temp['1688_product_url']   = 'https://detail.1688.com/offer/'.$v['1688_product_id'].'.html';
                   $temp['skuId']              = $v['skuId'];
                   $temp['specId']             = $v['specId'];
                   $temp['supply_id']          = $v['supply_id'];
                   $temp['1688_product_name']  = $v['1688_product_name'];
                   $temp['varient_colour']     = $v['varient_colour'];
                   $temp['varient_size']       = $v['varient_size'];
                   $temp['create_time']       = date("Y-m-d H:i:s", time());
                   $insert_arr[]               = $temp;
               }
           }
           if($insert_arr){
               Db::name('product_1688')->insertAll($insert_arr);
           }
    }


    /**
     * @desc   1688配对列表
     * @author luckyXiong
     * @date   2025-02-11
     */
    public function get_1688_product($params = []){
        $limit           = getIsset($params,'limit',10);
        $product_name    = getIsset($params,'product_name');
        $seller_sku      = getIsset($params,'seller_sku');
        $is_pair         = getIsset($params,'is_pair');
        $supply_id       = getIsset($params,'supply_id');
        $create_time     = getIsset($params,'create_time');
        $where           = [];

        if($product_name){
            $where[]     = ['spu', 'like', '%' . $product_name . '%'];
        }

        if($seller_sku){
            $where[] = ['seller_sku', '=', $seller_sku];
        }

        if ($create_time) {
            $where[]  = ['create_time', '>=', date('Y-m-d H:i:s',strtotime($create_time[0]))];
            $where[]  = ['create_time', '<=', date('Y-m-d H:i:s',strtotime($create_time[1]) + 3600*24-1)];
        }

        if($is_pair=='0' || $is_pair>0){
            $where[] = ['is_pair', '=',$is_pair];
        }

        if($supply_id){
            $where[] = ['supply_id','=' ,$supply_id];
        }

        $field = '*';
        $res   = Db::name('product_1688')
            ->field($field)
            ->where($where)
            ->order('create_time desc')
            ->paginate($limit);
        $list = $res->items()?:[];

        //批量获取产品大类;
        $supply_ids         = array_column($list,'supply_id');
        $supply_info        = Db::name('supply')->field('id,supply_name')->whereIn('id',$supply_ids)->select();
        $supply_info        = objectToArray($supply_info);
        $supply_info_map    = array_column($supply_info,null,'id');
        foreach($list as $k=>$v){
            $supply_names                = $supply_info_map[$v['supply_id']]??[];
            $list[$k]['supply_name']     = $supply_names['supply_name']??'';
            $list[$k]['varient_info']    = '颜色:'.$v['varient_colour']. ' 尺码:'.$v['varient_size'];
        }

        $data = [
            'list'   => $list,
            'total'  => $res->total(),
        ];
        return  $data;
    }






}